package com.guangbao.utils;

import java.io.IOException;
import java.util.Properties;

import redis.clients.jedis.Jedis;

public class JedisUtil {

	private static String host = "localhost";
	private static Integer port = 6379;

	static {
		try {
			Properties properties = new Properties();
			// 加载配置文件
			properties.load(JdbcUtil.class.getResourceAsStream("/redis.properties"));

			host = properties.getProperty("redis.host");
			port = Integer.parseInt(properties.getProperty("redis.port"));

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// 返回连接
	private static Jedis getConnection() {
		return new Jedis(host,port);
	}
	
	public static void set(String key,String value) {
		Jedis jedis = null;
		try {
			jedis = getConnection();
			jedis.set(key, value);
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			close(jedis);
		}
	}
	
	public static String get(String key) {
		Jedis jedis = null;
		try {
			jedis = getConnection();
			return jedis.get(key);
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			close(jedis);
		}
		return null;
	}
	
	public static void del(String key) {
		Jedis jedis = null;
		try {
			jedis = getConnection();
			if(jedis.exists(key)) {
				jedis.del(key);
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}finally {
			close(jedis);
		}
	}
	
	
	
	
	public static void close(Jedis jedis) {
		if(jedis != null)
			jedis.close();
	}
}
